package main

import (
	"log"
	"os"

	"github.com/gin-gonic/gin"
	"github.com/joho/godotenv"
	"gorm.io/driver/mysql"
	"gorm.io/driver/mongodb"
	"gorm.io/gorm"
	"production-tracker/config"
	"production-tracker/routes"
)

func main() {
	// 加载环境变量
	if err := godotenv.Load(); err != nil {
		log.Println("No .env file found")
	}

	// 初始化数据库
	var db *gorm.DB
	var err error

	dbType := os.Getenv("DB_TYPE")
	if dbType == "mongodb" {
		// MongoDB连接
		db, err = gorm.Open(mongodb.Open(os.Getenv("MONGODB_DSN")), &gorm.Config{})
	} else {
		// MySQL连接（默认）
		dsn := os.Getenv("MYSQL_DSN")
		if dsn == "" {
			dsn = "user:password@tcp(127.0.0.1:3306)/production_tracker?charset=utf8mb4&parseTime=True&loc=Local"
		}
		db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	}

	if err != nil {
		log.Fatal("Failed to connect to database:", err)
	}

	// 自动迁移数据库
	config.MigrateDB(db)

	// 初始化Gin
	r := gin.Default()
	
	// 配置CORS
	r.Use(func(c *gin.Context) {
		c.Header("Access-Control-Allow-Origin", "*")
		c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
		c.Header("Access-Control-Allow-Headers", "Origin, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
		
		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}
		
		c.Next()
	})

	// 注册路由
	routes.RegisterRoutes(r, db)

	// 启动服务器
	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}
	
	log.Printf("Server starting on port %s", port)
	r.Run(":" + port)
}
